var express = require('express');
var router = express.Router();
var User = require('../models/user.js');
var _ = require('underscore');

router.get("/", function (req, res, next) {
    User.find({}, function (err, users) {
        res.json(users);
    });
});
router.get("/:name", function (req, res, next) {
    var name = req.params.name;
    User.findOne({name: name}, function (err, user) {
        res.json(user);
    });
});

router.post("/new", function (req, res, next) {
    var userObj = req.body.user;
    var _user;
    var name = userObj.name;
    User.findOne({name: name}, function (err, data) {
        if (data) {
            console.log("User " + name + " already exists.")
        } else {
            _user = new User();
            _user = _.extend(_user, userObj);
            _user.save(function (err, user) {
                if (err) {
                    console.log("err", err.message);
                } else {
                    console.log("User:" + name + " save successful!");
                }
                res.redirect("/");
            });
        }
    });
});

router.post("/login", function (req, res, next) {
    var userObj = req.body.user;
    var name = userObj.name;
    User.findOne({name: name}, function (err, data) {
        if (data) {
            console.log("Login successful.");
            req.session.user = userObj;
            res.redirect("/");
        } else {
            console.log("User does not exist, please register.");
            res.redirect("/");
        }
    });
});

module.exports = router;